package com.ftw.commons.utils

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import java.io.File
import java.io.IOException

object ApkUtils {


    fun installAPk(context: Context, apkFile: File) {

        val installAPKIntent =
            getApkInStallIntent(
                context,
                apkFile
            )
        context.startActivity(installAPKIntent)

    }


    fun getApkInStallIntent(context: Context, apkFile: File): Intent {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.action = Intent.ACTION_VIEW

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            val uri = FileProvider.getUriForFile(
                context,
                context.packageName + ".update.provider",
                apkFile
            )
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
        } else {
            val uri = getApkUri(apkFile)
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
        }
        return intent
    }


    fun getApkUri(apkFile: File): Uri {
        try {
            val command = arrayOf("chmod", "777", apkFile.toString())
            val builder = ProcessBuilder(*command)
            builder.start()
        } catch (ignored: IOException) {
        }

        val uri = Uri.fromFile(apkFile)
        return uri
    }

    /**
     * 获取versionCode
     *
     * @param mContext
     * @return
     */
    fun getVersionCode(mContext: Context?): Int {
        if (mContext != null) {
            try {
                return mContext.packageManager.getPackageInfo(mContext.packageName, 0).versionCode
            } catch (ignored: PackageManager.NameNotFoundException) {
            }

        }
        return 0
    }

    /**
     * 获取versionName
     *
     * @param mContext
     * @return
     */
    fun getVersionName(mContext: Context?): String {
        if (mContext != null) {
            try {
                return mContext.packageManager.getPackageInfo(mContext.packageName, 0).versionName
            } catch (ignored: PackageManager.NameNotFoundException) {
            }

        }

        return ""
    }

}
